<!DOCTYPE html><html lang="zh-CN" data-theme="dark"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>Golang分支循环随机数 | J.のblog</title><meta name="keywords" content="云原生,golang"><meta name="author" content="J."><meta name="copyright" content="J."><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#0d0d0d"><meta name="description" content="分支、循环、随机数单分支if  condition &amp;#123;     代码块 &amp;#125;  if 5&gt;2 &amp;#123;     fmt.Println(&quot;5大于2&quot;) &amp;#125;   注意：Go语言中，花括号一定要跟着if、for、func等行的最后，否则语法出错。这其实就是为了解决C风格、Java风格之争。  condititon必须是一个bool类型，在GO中，不能使用其他类型等效为布">
<meta property="og:type" content="article">
<meta property="og:title" content="Golang分支循环随机数">
<meta property="og:url" content="http://dycloudnavite.love/2023/02/12/Golang%E5%88%86%E6%94%AF%E3%80%81%E5%BE%AA%E7%8E%AF%E3%80%81%E9%9A%8F%E6%9C%BA%E6%95%B0/index.html">
<meta property="og:site_name" content="J.のblog">
<meta property="og:description" content="分支、循环、随机数单分支if  condition &amp;#123;     代码块 &amp;#125;  if 5&gt;2 &amp;#123;     fmt.Println(&quot;5大于2&quot;) &amp;#125;   注意：Go语言中，花括号一定要跟着if、for、func等行的最后，否则语法出错。这其实就是为了解决C风格、Java风格之争。  condititon必须是一个bool类型，在GO中，不能使用其他类型等效为布">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://dycloudnavite.love/img/golang.png">
<meta property="article:published_time" content="2023-02-12T06:32:00.000Z">
<meta property="article:modified_time" content="2023-08-30T02:49:39.084Z">
<meta property="article:author" content="J.">
<meta property="article:tag" content="云原生">
<meta property="article:tag" content="golang">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://dycloudnavite.love/img/golang.png"><link rel="shortcut icon" href="/dujie5416/img/touxiang.png"><link rel="canonical" href="http://dycloudnavite.love/2023/02/12/Golang%E5%88%86%E6%94%AF%E3%80%81%E5%BE%AA%E7%8E%AF%E3%80%81%E9%9A%8F%E6%9C%BA%E6%95%B0/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/dujie5416/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/dujie5416/',
  algolia: {"appId":"9GWB2VV7GN","apiKey":"dac56ec5b0b1f45281251ee59db4d637","indexName":"blog","hits":{"per_page":6},"languages":{"input_placeholder":"搜索文章","hits_empty":"找不到您查询的内容：${query}","hits_stats":"找到 ${hits} 条结果，用时 ${time} 毫秒"}},
  localSearch: undefined,
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Golang分支循环随机数',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-08-30 10:49:39'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/xxx.css"><link rel="stylesheet" href="/css/universe.css"><link rel="stylesheet" href="/css/custom.css"><style type="text/css">#toggle-sidebar {bottom: 80px}</style><link rel="stylesheet" href="https://fastly.jsdelivr.net/gh/tzy13755126023/BLOG_SOURCE/css/function.min.css"><link rel="stylesheet" href="/css/rightMenu.css"><style type="text/css">#toggle-sidebar {left:100px}</style><!-- hexo injector head_end start --><link rel="stylesheet" href="https://cdn.cbd.int/hexo-butterfly-clock-anzhiyu/lib/clock.min.css" /><!-- hexo injector head_end end --><meta name="generator" content="Hexo 6.2.0"><link rel="alternate" href="/dujie5416/atom.xml" title="J.のblog" type="application/atom+xml">
</head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/dujie5416/img/touxiang.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/dujie5416/archives/"><div class="headline">文章</div><div class="length-num">73</div></a><a href="/dujie5416/tags/"><div class="headline">标签</div><div class="length-num">17</div></a><a href="/dujie5416/categories/"><div class="headline">分类</div><div class="length-num">11</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/dujie5416/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/dujie5416/img/longzhu.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/dujie5416/">J.のblog</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/dujie5416/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Golang分支循环随机数</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-02-12T06:32:00.000Z" title="发表于 2023-02-12 14:32:00">2023-02-12</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-08-30T02:49:39.084Z" title="更新于 2023-08-30 10:49:39">2023-08-30</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/dujie5416/categories/golang/">golang</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Golang分支循环随机数"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="分支、循环、随机数"><a href="#分支、循环、随机数" class="headerlink" title="分支、循环、随机数"></a>分支、循环、随机数</h1><h3 id="单分支"><a href="#单分支" class="headerlink" title="单分支"></a>单分支</h3><pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">if</span>  condition <span class="token punctuation">&#123;</span>
    代码块
<span class="token punctuation">&#125;</span>

<span class="token keyword">if</span> <span class="token number">5</span><span class="token operator">></span><span class="token number">2</span> <span class="token punctuation">&#123;</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"5大于2"</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<p>注意：Go语言中，花括号一定要跟着if、for、func等行的最后，否则语法出错。这其实就是为了解决C风格、Java风格之争。</p>
<ul>
<li>condititon<strong>必须是一个bool类型</strong>，在GO中，<strong>不能</strong>使用其他类型等效为布尔值。<code>if 1&#123;&#125; </code>是错误的</li>
<li>语句块中可以写其他代码</li>
<li>如果conditition为true，才能执行其后代码块</li>
</ul>
<h3 id="多分支"><a href="#多分支" class="headerlink" title="多分支"></a>多分支</h3><pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">if</span> condition1 <span class="token punctuation">&#123;</span>
    代码块<span class="token number">1</span>
<span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token keyword">if</span> condition2 <span class="token punctuation">&#123;</span>
    代码块<span class="token number">2</span>
<span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token keyword">if</span> condition3 <span class="token punctuation">&#123;</span>
    代码块<span class="token number">3</span>
<span class="token punctuation">&#125;</span> <span class="token operator">...</span> <span class="token punctuation">&#123;</span>
    <span class="token operator">...</span>
<span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token keyword">if</span> conditionN <span class="token punctuation">&#123;</span>
    代码块N
<span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
    代码块
<span class="token punctuation">&#125;</span>

a <span class="token operator">:=</span> <span class="token number">6</span>
<span class="token keyword">if</span> a <span class="token operator">&lt;</span> <span class="token number">0</span> <span class="token punctuation">&#123;</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"negative"</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token keyword">if</span> a <span class="token operator">></span> <span class="token number">0</span> <span class="token punctuation">&#123;</span> <span class="token comment">// 走到这里一定 a 不小于 0</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"positive"</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span> <span class="token comment">// 走到这里一定 a 不大于、也不小于 0</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"zero"</span><span class="token punctuation">)</span> <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ul>
<li>多分支结构，从上向下依次判断分支条件，只要一个分支条件成立，其后语句块将被执行，那么其他条件都不会被执行</li>
<li>前一个分支条件被测试过，下一个条件相当于隐含着这个条件</li>
<li>一定要考虑一下else分之是否有必要写，以防逻辑漏洞</li>
</ul>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// 嵌套</span>
a <span class="token operator">:=</span> <span class="token number">6</span>
<span class="token keyword">if</span> a <span class="token operator">==</span> <span class="token number">0</span> <span class="token punctuation">&#123;</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"zero"</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
 <span class="token keyword">if</span> a <span class="token operator">></span> <span class="token number">0</span> <span class="token punctuation">&#123;</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"negative"</span><span class="token punctuation">)</span>
 <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token keyword">if</span> a <span class="token operator">>=</span> <span class="token number">0</span> <span class="token punctuation">&#123;</span> <span class="token comment">// 走到这里一定 a 不小于 0</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"positive"</span><span class="token punctuation">)</span>
 <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>循环也可以互相嵌套，形成多层循环， 循环嵌套不宜过深。</p>
<h3 id="switch-分支"><a href="#switch-分支" class="headerlink" title="switch 分支"></a>switch 分支</h3><p>特别注意：GO语言的switch有别于C语言的switch，case是独立代码块，不能穿透。</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">a <span class="token operator">:=</span> <span class="token number">20</span>
<span class="token keyword">switch</span> a <span class="token punctuation">&#123;</span> <span class="token comment">// 待比较的是a</span>
<span class="token keyword">case</span> <span class="token number">10</span><span class="token punctuation">:</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"ten"</span><span class="token punctuation">)</span>
<span class="token keyword">case</span> <span class="token number">20</span><span class="token punctuation">:</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"twenty"</span><span class="token punctuation">)</span>
<span class="token keyword">case</span> <span class="token number">30</span><span class="token punctuation">,</span> <span class="token number">40</span><span class="token punctuation">,</span> <span class="token number">50</span><span class="token punctuation">:</span> <span class="token comment">// 或关系</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">">=30 and &lt;=50"</span><span class="token punctuation">)</span>
<span class="token keyword">default</span><span class="token punctuation">:</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"other"</span><span class="token punctuation">)</span> <span class="token punctuation">&#125;</span>

或写成
<span class="token keyword">switch</span> a<span class="token operator">:=</span><span class="token number">20</span><span class="token punctuation">;</span>a <span class="token punctuation">&#123;</span> <span class="token comment">// 待比较的是a</span>
<span class="token keyword">case</span> <span class="token number">10</span><span class="token punctuation">:</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"ten"</span><span class="token punctuation">)</span>
<span class="token keyword">case</span> <span class="token number">20</span><span class="token punctuation">:</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"twenty"</span><span class="token punctuation">)</span>
<span class="token keyword">case</span> <span class="token number">30</span><span class="token punctuation">,</span> <span class="token number">40</span><span class="token punctuation">,</span> <span class="token number">50</span><span class="token punctuation">:</span> <span class="token comment">// 或关系</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">">=30 and &lt;=50"</span><span class="token punctuation">)</span>
<span class="token keyword">default</span><span class="token punctuation">:</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"other"</span><span class="token punctuation">)</span> <span class="token punctuation">&#125;</span>
<span class="token comment">// 上面2种写法a的作用域有区别，这个后面再说</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<pre class="line-numbers language-go" data-language="go"><code class="language-go">a <span class="token operator">:=</span> <span class="token number">20</span>
<span class="token keyword">switch</span> <span class="token punctuation">&#123;</span> <span class="token comment">// 没有待比较变量，意味着表达式是true，是布尔型</span>
<span class="token keyword">case</span> a <span class="token operator">></span> <span class="token number">0</span><span class="token punctuation">:</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"positive"</span><span class="token punctuation">)</span>
<span class="token keyword">case</span> a <span class="token operator">&lt;</span> <span class="token number">0</span><span class="token punctuation">:</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"negative"</span><span class="token punctuation">)</span>
<span class="token keyword">default</span><span class="token punctuation">:</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"zero"</span><span class="token punctuation">)</span> <span class="token punctuation">&#125;</span>
或写成
<span class="token keyword">switch</span> a <span class="token operator">:=</span> <span class="token number">20</span><span class="token punctuation">;</span> <span class="token punctuation">&#123;</span> <span class="token comment">// 没有待比较变量，意味着表达式是true，是布尔型</span>
<span class="token keyword">case</span> a <span class="token operator">></span> <span class="token number">0</span><span class="token punctuation">:</span> <span class="token comment">// 如果待比较值是true，a > 0如果返回true，就进入</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"positive"</span><span class="token punctuation">)</span>
 <span class="token comment">// fallthrough // 穿透</span>
<span class="token keyword">case</span> a <span class="token operator">&lt;</span> <span class="token number">0</span><span class="token punctuation">:</span> <span class="token comment">// 如果待比较值是true，a &lt; 0如果返回true，就进入</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"negative"</span><span class="token punctuation">)</span>
<span class="token keyword">default</span><span class="token punctuation">:</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"zero"</span><span class="token punctuation">)</span> <span class="token punctuation">&#125;</span>
<span class="token comment">// 上面2种写法a的作用域有区别，这个后面再说</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<p>C语言的switch有穿透效果，而Go语言没有。如果想在Go语言中实现穿透效果，使用<code>fallthrough</code>穿透当前<code>case</code>语句块。但是，大家使用C语言的时候，一般都不想要使用这种穿透效果，所以，如非必要，不要使用<code>fallthrough</code>。</p>
<h3 id="特殊if"><a href="#特殊if" class="headerlink" title="特殊if"></a>特殊if</h3><p>switch可以写成 switch a:&#x3D;20;a 这种形式，也就是可以在表达式a之前写一个语句后接一个分号。if也可以这样</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">if</span> score<span class="token punctuation">,</span> line <span class="token operator">:=</span> <span class="token number">99</span><span class="token punctuation">,</span> <span class="token number">90</span><span class="token punctuation">;</span> score <span class="token operator">></span> line <span class="token punctuation">&#123;</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"perfect"</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"good"</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span> <span class="token comment">// score, line作用域只能是当前if语句</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这种写法中定义idea变量作用域只能是当前if或switch</p>
<h3 id="for循环"><a href="#for循环" class="headerlink" title="for循环"></a>for循环</h3><h5 id="C风格循环"><a href="#C风格循环" class="headerlink" title="C风格循环"></a>C风格循环</h5><pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">for</span> <span class="token punctuation">[</span>初始操作<span class="token punctuation">]</span><span class="token punctuation">;</span><span class="token punctuation">[</span>循环条件<span class="token punctuation">]</span><span class="token punctuation">;</span><span class="token punctuation">[</span>循环后操作<span class="token punctuation">]</span> <span class="token punctuation">&#123;</span>
    循环体
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>


<ul>
<li>初始操作：第一次进入循环前执行，语句只能执行一次，之后不再执行</li>
<li>循环条件：要求返回布尔值，每次进入循环体前进行判断。如果每次条件满足返回true，就进入循环执行一次循环体；否则，循环结束</li>
<li>循环后操作：每次循环体执行完，在执行下一趟循环条件判断之前，执行该操作一次</li>
</ul>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">for</span> i <span class="token operator">:=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token number">10</span><span class="token punctuation">;</span> i<span class="token operator">++</span> <span class="token punctuation">&#123;</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>i<span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span> <span class="token comment">// 初始操作中的短格式定义的i的作用域只能在for中</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// 特殊写法</span>
<span class="token keyword">for</span> i <span class="token operator">:=</span> <span class="token number">5</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token number">10</span><span class="token punctuation">;</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
<span class="token keyword">for</span> i <span class="token operator">:=</span> <span class="token number">5</span><span class="token punctuation">;</span> <span class="token punctuation">;</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span> <span class="token comment">// 没条件就相当于true</span>
<span class="token keyword">for</span> i <span class="token operator">&lt;</span> <span class="token number">10</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span> <span class="token comment">// for condition &#123;&#125;，condition就是循环条件</span>
<span class="token keyword">for</span> <span class="token punctuation">;</span><span class="token punctuation">;</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span> <span class="token comment">// 死循环</span>
<span class="token comment">// 死循环简写如下</span>
<span class="token keyword">for</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span> <span class="token comment">// 死循环 相对于 for true &#123;&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="continue"><a href="#continue" class="headerlink" title="continue"></a>continue</h6><p>中止当前这一趟循环的执行，直接执行循环后操作，进入下一趟的条件判断</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">for</span> i <span class="token operator">:=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token number">10</span><span class="token punctuation">;</span> i<span class="token operator">++</span> <span class="token punctuation">&#123;</span>
 <span class="token keyword">if</span> i<span class="token operator">%</span><span class="token number">2</span> <span class="token operator">==</span> <span class="token number">0</span> <span class="token punctuation">&#123;</span>
 <span class="token keyword">continue</span>
 <span class="token punctuation">&#125;</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>i<span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span> <span class="token comment">// 请问执行结果是什么？1,3,5,7,9</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<h6 id="break"><a href="#break" class="headerlink" title="break"></a>break</h6><p>终止当前循环的执行，直接结束</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">for</span> i <span class="token operator">:=</span> <span class="token number">0</span><span class="token punctuation">;</span> <span class="token punctuation">;</span> i<span class="token operator">++</span> <span class="token punctuation">&#123;</span>
 <span class="token keyword">if</span> i<span class="token operator">%</span><span class="token number">2</span> <span class="token operator">==</span> <span class="token number">0</span> <span class="token punctuation">&#123;</span>
 <span class="token keyword">continue</span>
 <span class="token punctuation">&#125;</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>i<span class="token punctuation">)</span>
 <span class="token keyword">if</span> i <span class="token operator">>=</span> <span class="token number">10</span> <span class="token punctuation">&#123;</span>
 <span class="token keyword">break</span>
 <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span> <span class="token comment">// 请问执行结果是什么？1,3,5,7,9,11</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>除了break，函数的return结束函数执行，当然也能把函数中的循环打断。</p>
<h6 id="goto和label"><a href="#goto和label" class="headerlink" title="goto和label"></a><strong>goto和label</strong></h6><p>它会破坏结构化编程，但是确实能做到便利的无条件跳转</p>
<ul>
<li>跳出多重循环使用，但是为什么要用多重循环？？？？？？</li>
<li>到同一处标签统一处理，例如统一错误处理，问题是，写个函数也能实现为啥用你？？？</li>
</ul>
<p>goto需要配合标签label使用，label就像代码中的锚点，goto将无条件调到那里开始向后执行代码。</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">for</span> i <span class="token operator">:=</span> <span class="token number">0</span><span class="token punctuation">;</span> <span class="token punctuation">;</span> i<span class="token operator">++</span> <span class="token punctuation">&#123;</span>
 <span class="token keyword">if</span> i<span class="token operator">%</span><span class="token number">2</span> <span class="token operator">==</span> <span class="token number">0</span> <span class="token punctuation">&#123;</span>
 <span class="token keyword">continue</span>
 <span class="token punctuation">&#125;</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>i<span class="token punctuation">)</span>
 <span class="token keyword">if</span> i <span class="token operator">></span> <span class="token number">10</span> <span class="token punctuation">&#123;</span>
 <span class="token keyword">goto</span> condition
 <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>
condition<span class="token punctuation">:</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"done"</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>continue、break也可以指定label，方便某些循环使用。但是，建议不要这么写，弄不好就成了毛线团。</p>
<h5 id="for-range"><a href="#for-range" class="headerlink" title="for range"></a>for range</h5><table>
<thead>
<tr>
<th>类型</th>
<th>变量</th>
<th>Range expression</th>
<th>第一个值</th>
<th>第二个值</th>
</tr>
</thead>
<tbody><tr>
<td>array or slice</td>
<td>a</td>
<td>[n]E, *[n]E []E</td>
<td>index i int</td>
<td>a[i]E</td>
</tr>
<tr>
<td>string</td>
<td>s</td>
<td>“abcd”</td>
<td>index i int utf-8字节偏移</td>
<td>unicode值  rune</td>
</tr>
<tr>
<td>map</td>
<td>m</td>
<td>map[K]V</td>
<td>key k K</td>
<td>m[k]V</td>
</tr>
<tr>
<td>channel</td>
<td>c</td>
<td>chan E, &lt;-chan E<br>通道或只读通道</td>
<td>element e E</td>
<td>无</td>
</tr>
</tbody></table>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token string">"测试"</span>  utf<span class="token operator">-</span><span class="token number">8</span> 编码为 <span class="token string">"\xe6\xb5\x8b\xe8\xaf\x95"</span>
<span class="token keyword">for</span> i<span class="token punctuation">,</span> v <span class="token operator">:=</span> <span class="token keyword">range</span> <span class="token string">"abcd测试"</span> <span class="token punctuation">&#123;</span>
 fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"%d, %[2]d, %[2]c, %#[2]x\n"</span><span class="token punctuation">,</span> i<span class="token punctuation">,</span> v<span class="token punctuation">)</span> <span class="token punctuation">&#125;</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"\xe6\xb5\x8b\xe8\xaf\x95"</span><span class="token punctuation">)</span> <span class="token comment">// 6个字节</span>
运行结果如下
<span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">97</span><span class="token punctuation">,</span> a<span class="token punctuation">,</span> <span class="token number">0x61</span>
<span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">98</span><span class="token punctuation">,</span> b<span class="token punctuation">,</span> <span class="token number">0x62</span>
<span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">99</span><span class="token punctuation">,</span> c<span class="token punctuation">,</span> <span class="token number">0x63</span>
<span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">100</span><span class="token punctuation">,</span> d<span class="token punctuation">,</span> <span class="token number">0x64</span>
<span class="token number">4</span><span class="token punctuation">,</span> <span class="token number">27979</span><span class="token punctuation">,</span> 测<span class="token punctuation">,</span> <span class="token number">0x6d4b</span>
<span class="token number">7</span><span class="token punctuation">,</span> <span class="token number">35797</span><span class="token punctuation">,</span> 试<span class="token punctuation">,</span> <span class="token number">0x8bd5</span>
测试
索引就是字节偏移量，从索引可以看出，中文在字符串中是utf<span class="token operator">-</span><span class="token number">8</span>编码，占<span class="token number">3</span>个字节。
但是<span class="token keyword">for</span> <span class="token keyword">range</span>读取字符串返回的是一个个字符（整数），而字符是ASCII或UNICODE对应的编码值。
<span class="token operator">%</span>d 打印的是unicode值 <span class="token operator">%</span>c 打印的是字符<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">arr <span class="token operator">:=</span> <span class="token punctuation">[</span><span class="token number">5</span><span class="token punctuation">]</span><span class="token builtin">int</span><span class="token punctuation">&#123;</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">,</span> <span class="token number">7</span><span class="token punctuation">,</span> <span class="token number">9</span><span class="token punctuation">&#125;</span>
<span class="token keyword">for</span> i<span class="token punctuation">,</span> v <span class="token operator">:=</span> <span class="token keyword">range</span> arr <span class="token punctuation">&#123;</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>i<span class="token punctuation">,</span> v<span class="token punctuation">,</span> arr<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>
<span class="token comment">// 只打印索引</span>
<span class="token keyword">for</span> i <span class="token operator">:=</span> <span class="token keyword">range</span> arr <span class="token punctuation">&#123;</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>i<span class="token punctuation">,</span> arr<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>
<span class="token comment">// 只打印值</span>
<span class="token keyword">for</span> <span class="token boolean">_</span><span class="token punctuation">,</span> v <span class="token operator">:=</span> <span class="token keyword">range</span> arr <span class="token punctuation">&#123;</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>v<span class="token punctuation">)</span> <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<h3 id="随机数"><a href="#随机数" class="headerlink" title="随机数"></a>随机数</h3><p>标准库”math&#x2F;rand”</p>
<p>我们使用的是伪随机数，是内部写好的公式计算出来的。这个公式运行提供一个种子，有这个种子作为起始值开始计算。</p>
<ul>
<li>src :&#x3D; rand.NewSource(100)，使用种子100 创建一个随机数源</li>
<li>rand.New(rand.NewSource(time.Now().UnixNano())) ，利用当前时间的纳秒值做种子</li>
<li>r10 :&#x3D; rand.New(src)，使用源创建随机数生成器</li>
<li>r10.Intn(5)，返回[0,5)的随机整数</li>
</ul>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token punctuation">(</span>
 <span class="token string">"fmt"</span>
 <span class="token string">"math/rand"</span>
<span class="token punctuation">)</span>
<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
 src <span class="token operator">:=</span> rand<span class="token punctuation">.</span><span class="token function">NewSource</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span>
 r10 <span class="token operator">:=</span> rand<span class="token punctuation">.</span><span class="token function">New</span><span class="token punctuation">(</span>src<span class="token punctuation">)</span>
 r1 <span class="token operator">:=</span> rand<span class="token punctuation">.</span><span class="token function">New</span><span class="token punctuation">(</span>rand<span class="token punctuation">.</span><span class="token function">NewSource</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
 <span class="token keyword">for</span> i <span class="token operator">:=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token number">10</span><span class="token punctuation">;</span> i<span class="token operator">++</span> <span class="token punctuation">&#123;</span>
 fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"%d, %d, %d\n"</span><span class="token punctuation">,</span> rand<span class="token punctuation">.</span><span class="token function">Intn</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">,</span> r1<span class="token punctuation">.</span><span class="token function">Intn</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">,</span> r10<span class="token punctuation">.</span><span class="token function">Intn</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
 <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>全局随机数生成器globalRand</p>
<ul>
<li>他的种子默认为1，<code>var globalRand = New(&amp;lockedSource&#123;src: NewSource(1).(*rngSource)&#125;)</code></li>
<li>如果要改变globalRand的种子，就需要使用rand.Seed(2)修改种子</li>
<li><code>rand.Intn(5)</code> 就是使用它生成随机数</li>
</ul>
<p>从Go v1.20开始，globalRand已经改变为使用随机种子。可以查看官网<a target="_blank" rel="noopener" href="https://go.dev/doc/go1.20">https://go.dev/doc/go1.20</a></p>
<p>如果想使用旧版globalRand的行为，可以手动设定种子源<code>rand.Seed(1)</code> 或使用环境变量<code>os.Setenv(&quot;GODEBUG&quot;,&quot;randautoseed=0&quot;)</code></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="http://dycloudnavite.love">J.</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://dycloudnavite.love/2023/02/12/Golang%E5%88%86%E6%94%AF%E3%80%81%E5%BE%AA%E7%8E%AF%E3%80%81%E9%9A%8F%E6%9C%BA%E6%95%B0/">http://dycloudnavite.love/2023/02/12/Golang%E5%88%86%E6%94%AF%E3%80%81%E5%BE%AA%E7%8E%AF%E3%80%81%E9%9A%8F%E6%9C%BA%E6%95%B0/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://dycloudnavite.love" target="_blank">J.のblog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/dujie5416/tags/%E4%BA%91%E5%8E%9F%E7%94%9F/">云原生</a><a class="post-meta__tags" href="/dujie5416/tags/golang/">golang</a></div><div class="post_share"><div class="addthis_inline_share_toolbox"></div><script src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-5d034d84b42927bf" async="async"></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/dujie5416/img/wechat.jpg" target="_blank"><img class="post-qr-code-img" src="/dujie5416/img/wechat.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/dujie5416/img/alipay.jpg" target="_blank"><img class="post-qr-code-img" src="/dujie5416/img/alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/dujie5416/2023/02/13/Golang%E5%AD%97%E7%AC%A6%E4%B8%B2string/"><img class="prev-cover" src="/dujie5416/img/golang.png" onerror="onerror=null;src='/dujie5416/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Golang字符串</div></div></a></div><div class="next-post pull-right"><a href="/dujie5416/2023/02/12/Golang%E7%BA%BF%E6%80%A7%E8%A1%A8-%E6%95%B0%E7%BB%84%E3%80%81%E5%88%87%E7%89%87/"><img class="next-cover" src="/dujie5416/img/golang.png" onerror="onerror=null;src='/dujie5416/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Golang线性表-数组、切片</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/dujie5416/2023/05/20/Channel%E9%80%9A%E9%81%93/" title="Channel通道"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-05-20</div><div class="title">Channel通道</div></div></a></div><div><a href="/dujie5416/2023/05/06/Golang%E4%B8%AD%E7%9A%84GORM/" title="Golang GORM使用"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-05-06</div><div class="title">Golang GORM使用</div></div></a></div><div><a href="/dujie5416/2023/06/23/Gin%E6%A1%86%E6%9E%B6/" title="Gin框架"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-06-23</div><div class="title">Gin框架</div></div></a></div><div><a href="/dujie5416/2023/05/15/Golang%E5%8D%8F%E7%A8%8B/" title="Golang协程"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-05-15</div><div class="title">Golang协程</div></div></a></div><div><a href="/dujie5416/2023/04/17/Golang%E5%8F%98%E9%87%8F%E9%80%83%E9%80%B8%E2%80%94%E2%80%94%E5%A0%86%E3%80%81%E6%A0%88/" title="Golang变量逃逸————堆、栈"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-04-17</div><div class="title">Golang变量逃逸————堆、栈</div></div></a></div><div><a href="/dujie5416/2023/02/13/Golang%E5%AD%97%E7%AC%A6%E4%B8%B2string/" title="Golang字符串"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-02-13</div><div class="title">Golang字符串</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="lv-container" data-id="city" data-uid="MTAyMC81Njk5OS8zMzQ2Mw=="></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/dujie5416/img/touxiang.png" onerror="this.onerror=null;this.src='/dujie5416/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">J.</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/dujie5416/archives/"><div class="headline">文章</div><div class="length-num">73</div></a><a href="/dujie5416/tags/"><div class="headline">标签</div><div class="length-num">17</div></a><a href="/dujie5416/categories/"><div class="headline">分类</div><div class="length-num">11</div></a></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%88%86%E6%94%AF%E3%80%81%E5%BE%AA%E7%8E%AF%E3%80%81%E9%9A%8F%E6%9C%BA%E6%95%B0"><span class="toc-number">1.</span> <span class="toc-text">分支、循环、随机数</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8D%95%E5%88%86%E6%94%AF"><span class="toc-number">1.0.1.</span> <span class="toc-text">单分支</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%A4%9A%E5%88%86%E6%94%AF"><span class="toc-number">1.0.2.</span> <span class="toc-text">多分支</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#switch-%E5%88%86%E6%94%AF"><span class="toc-number">1.0.3.</span> <span class="toc-text">switch 分支</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%89%B9%E6%AE%8Aif"><span class="toc-number">1.0.4.</span> <span class="toc-text">特殊if</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#for%E5%BE%AA%E7%8E%AF"><span class="toc-number">1.0.5.</span> <span class="toc-text">for循环</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#C%E9%A3%8E%E6%A0%BC%E5%BE%AA%E7%8E%AF"><span class="toc-number">1.0.5.0.1.</span> <span class="toc-text">C风格循环</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#continue"><span class="toc-number">1.0.5.0.1.1.</span> <span class="toc-text">continue</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#break"><span class="toc-number">1.0.5.0.1.2.</span> <span class="toc-text">break</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#goto%E5%92%8Clabel"><span class="toc-number">1.0.5.0.1.3.</span> <span class="toc-text">goto和label</span></a></li></ol></li><li class="toc-item toc-level-5"><a class="toc-link" href="#for-range"><span class="toc-number">1.0.5.0.2.</span> <span class="toc-text">for range</span></a></li></ol></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%9A%8F%E6%9C%BA%E6%95%B0"><span class="toc-number">1.0.6.</span> <span class="toc-text">随机数</span></a></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/07/29/%E6%A0%B9%E6%8D%AErouter%E6%98%BE%E7%A4%BA%E5%B7%A6%E4%BE%A7%E8%8F%9C%E5%8D%95%E6%A0%8F%E9%9A%90%E8%97%8F%E6%9F%90%E4%B8%AA%E8%8F%9C%E5%8D%95%E9%80%89%E9%A1%B9/" title="vue3左侧菜单隐藏某选项"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="vue3左侧菜单隐藏某选项"/></a><div class="content"><a class="title" href="/dujie5416/2023/07/29/%E6%A0%B9%E6%8D%AErouter%E6%98%BE%E7%A4%BA%E5%B7%A6%E4%BE%A7%E8%8F%9C%E5%8D%95%E6%A0%8F%E9%9A%90%E8%97%8F%E6%9F%90%E4%B8%AA%E8%8F%9C%E5%8D%95%E9%80%89%E9%A1%B9/" title="vue3左侧菜单隐藏某选项">vue3左侧菜单隐藏某选项</a><time datetime="2023-07-29T06:32:00.000Z" title="发表于 2023-07-29 14:32:00">2023-07-29</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/07/13/Vue%E7%8A%B6%E6%80%81%E7%AE%A1%E7%90%86/" title="Vue状态管理"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="Vue状态管理"/></a><div class="content"><a class="title" href="/dujie5416/2023/07/13/Vue%E7%8A%B6%E6%80%81%E7%AE%A1%E7%90%86/" title="Vue状态管理">Vue状态管理</a><time datetime="2023-07-13T09:29:00.000Z" title="发表于 2023-07-13 17:29:00">2023-07-13</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/06/27/%E5%9F%BA%E4%BA%8EIOC%E8%A7%A3%E5%86%B3%E5%AF%B9%E8%B1%A1%E4%BE%9D%E8%B5%96%E9%97%AE%E9%A2%98/" title="基于IOC解决对象依赖问题"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="基于IOC解决对象依赖问题"/></a><div class="content"><a class="title" href="/dujie5416/2023/06/27/%E5%9F%BA%E4%BA%8EIOC%E8%A7%A3%E5%86%B3%E5%AF%B9%E8%B1%A1%E4%BE%9D%E8%B5%96%E9%97%AE%E9%A2%98/" title="基于IOC解决对象依赖问题">基于IOC解决对象依赖问题</a><time datetime="2023-06-27T03:32:00.000Z" title="发表于 2023-06-27 11:32:00">2023-06-27</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/06/23/Gin%E6%A1%86%E6%9E%B6/" title="Gin框架"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="Gin框架"/></a><div class="content"><a class="title" href="/dujie5416/2023/06/23/Gin%E6%A1%86%E6%9E%B6/" title="Gin框架">Gin框架</a><time datetime="2023-06-23T06:32:00.000Z" title="发表于 2023-06-23 14:32:00">2023-06-23</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/06/04/ServeMux%E3%80%81httprouter/" title="ServeMux、httprouter"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="ServeMux、httprouter"/></a><div class="content"><a class="title" href="/dujie5416/2023/06/04/ServeMux%E3%80%81httprouter/" title="ServeMux、httprouter">ServeMux、httprouter</a><time datetime="2023-06-04T03:32:00.000Z" title="发表于 2023-06-04 11:32:00">2023-06-04</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('/dujie5416/img/longzhu.png')"><div id="footer-wrap"><div class="copyright">&copy;2019 - 2024  <i id="heartbeat" class="fa fas fa-heartbeat"></i> J.</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a><a href="http://beian.miit.gov.cn/"  style="color:#f72b07" target="_blank">京ICP备2022023567号</a></div></div><link rel="stylesheet" href="https://fastly.jsdelivr.net/gh/HCLonely/images@master/others/heartbeat.min.css"></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="algolia-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="search-wrap"><div id="algolia-search-input"></div><hr/><div id="algolia-search-results"><div id="algolia-hits"></div><div id="algolia-pagination"></div><div id="algolia-info"><div class="algolia-stats"></div><div class="algolia-poweredBy"></div></div></div></div></div><div id="search-mask"></div></div><div id="rightMenu"><div class="rightMenu-group rightMenu-small"><div class="rightMenu-item" id="menu-backward"><i class="fa-solid fa-arrow-left"></i></div><div class="rightMenu-item" id="menu-forward"><i class="fa-solid fa-arrow-right"></i></div><div class="rightMenu-item" id="menu-refresh"><i class="fa-solid fa-arrow-rotate-right"></i></div><div class="rightMenu-item" id="menu-home"><i class="fa-solid fa-house"></i></div></div><div class="rightMenu-group rightMenu-line rightMenuOther"><a class="rightMenu-item menu-link" href="/archives/"><i class="fa-solid fa-archive"></i><span>文章归档</span></a><a class="rightMenu-item menu-link" href="/categories/"><i class="fa-solid fa-folder-open"></i><span>文章分类</span></a><a class="rightMenu-item menu-link" href="/tags/"><i class="fa-solid fa-tags"></i><span>文章标签</span></a></div><div class="rightMenu-group rightMenu-line rightMenuNormal"><a class="rightMenu-item menu-link" id="menu-radompage" href="/random/index.html"><i class="fa-solid fa-shoe-prints"></i><span>随便逛逛</span></a><div class="rightMenu-item" id="menu-translate"><i class="fa-solid fa-earth-asia"></i><span>繁简切换</span></div><div class="rightMenu-item" id="menu-darkmode"><i class="fa-solid fa-moon"></i><span>切换模式</span></div></div></div><div id="rightmenu-mask"></div><div><script src="/dujie5416/js/utils.js"></script><script src="/dujie5416/js/main.js"></script><script src="/dujie5416/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/algoliasearch/dist/algoliasearch-lite.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instantsearch.js/dist/instantsearch.production.min.js"></script><script src="/dujie5416/js/search/algolia.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><script>function loadLivere () {
  if (typeof LivereTower === 'object') {
    window.LivereTower.init()
  }
  else {
    (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
    })(document, 'script');
  }
}

if ('Livere' === 'Livere' || !false) {
  if (false) btf.loadComment(document.getElementById('lv-container'), loadLivere)
  else loadLivere()
}
else {
  function loadOtherComment () {
    loadLivere()
  }
}</script></div><script defer src="https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js"></script><script data-pjax defer src="https://npm.elemecdn.com/tzy-blog/lib/js/theme/chocolate.js"></script><canvas id="universe"></canvas><script defer src="/js/universe.js"></script><script defer data-pjax src="/js/rightMenu.js"></script><div class="aplayer no-destroy" data-id="7427714271" data-server="netease" data-type="playlist" data-fixed="true" data-mini="true" data-listFolded="false" data-order="random" data-lrctype="1" data-preload="none" data-autoplay="true" muted></div><script id="click-show-text" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/click-show-text.min.js" data-mobile="false" data-text="I,LOVE,YOU" data-fontsize="15px" data-random="false" async="async"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/metingjs/dist/Meting.min.js"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = ["meta[property=\"og:image\"]","meta[property=\"og:title\"]","meta[property=\"og:url\"]","head > title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show",".js-pjax"]

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.tocScrollFn && window.removeEventListener('scroll', window.tocScrollFn)
  window.scrollCollect && window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  document.getElementById('rightside').style.cssText = "opacity: ''; transform: ''"
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

  typeof disqusjs === 'object' && disqusjs.destroy()
})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><!-- hexo injector body_end start --><script data-pjax>
  function butterfly_clock_anzhiyu_injector_config(){
    var parent_div_git = document.getElementsByClassName('sticky_layout')[0];
    var item_html = '<div class="card-widget card-clock"><div class="card-glass"><div class="card-background"><div class="card-content"><div id="hexo_electric_clock"><img class="entered loading" id="card-clock-loading" src="https://cdn.cbd.int/hexo-butterfly-clock-anzhiyu/lib/loading.gif" style="height: 120px; width: 100%;" data-ll-status="loading"/></div></div></div></div></div>';
    console.log('已挂载butterfly_clock_anzhiyu')
    if(parent_div_git) {
      parent_div_git.insertAdjacentHTML("afterbegin",item_html)
    }
  }
  var elist = 'null'.split(',');
  var cpage = location.pathname;
  var epage = 'all';
  var qweather_key = '56289903f0d448dfbe8262dba0175f70';
  var gaud_map_key = '01603f2b2d08d0e947bb101e9d9b148b';
  var baidu_ak_key = 'undefined';
  var flag = 0;
  var clock_rectangle = '112.982279,28.19409';
  var clock_default_rectangle_enable = 'false';

  for (var i=0;i<elist.length;i++){
    if (cpage.includes(elist[i])){
      flag++;
    }
  }

  if ((epage ==='all')&&(flag == 0)){
    butterfly_clock_anzhiyu_injector_config();
  }
  else if (epage === cpage){
    butterfly_clock_anzhiyu_injector_config();
  }
  </script><script src="https://widget.qweather.net/simple/static/js/he-simple-common.js?v=2.0"></script><script data-pjax src="https://cdn.cbd.int/hexo-butterfly-clock-anzhiyu/lib/clock.min.js"></script><!-- hexo injector body_end end --><script src="/dujie5416/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"tagMode":false,"debug":false,"model":{"jsonPath":"/dujie5416/live2dw/assets/tororo.model.json"},"display":{"position":"right","width":150,"height":350,"hOffset":20,"vOffset":-20},"mobile":{"show":false},"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/"});</script><script async>window.onload=function(){var a=document.createElement('script'),b=document.getElementsByTagName('script')[0];a.type='text/javascript',a.async=!0,a.src='/sw-register.js?v='+Date.now(),b.parentNode.insertBefore(a,b)};</script></body></html>